package com.yiwei.zxp.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.LoginSuccessEvent;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.QRCode;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.InviteShareDilaog;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class InviteActivity extends BaseActivity implements InviteShareDilaog.OnChooseListener {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.btn_share)
    ImageView btnShare;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.webview)
    FrameLayout mWebContainer;
    private Unbinder unbiner;
    private WebView mWebView;
    private String title;
    private String description;
    private String shareUrl;
    private String shareImage = "";
    private boolean isSava = false;
    private InviteShareDilaog inviteShareDilaog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        inviteShareDilaog = new InviteShareDilaog(this).setOnChooseListener(this);
        title = getIntent().getStringExtra("title");
        description = getIntent().getStringExtra("description");
        mWebView = new WebView(getApplicationContext());
        mWebContainer.addView(mWebView);
        txtTitle.setText("邀请有礼");
        getShareIndex();
    }


    public void getShareIndex() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();

        Api.api_service.getShareIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setWebView(result.datas.link);
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginSuccessEvent event) {
        getShareIndex();
    }


    private void setWebView(String content) {
        mWebContainer.setVisibility(View.VISIBLE);
        mWebView.setBackgroundColor(0);
        if (Build.VERSION.SDK_INT >= 21) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
//        mWebView.setWebChromeClient(new WebChromeClient());
        // // 设置可以支持缩放
//        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.addJavascriptInterface(new JsToJava1(), "appmethod");
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");
        mWebView.setWebViewClient(new WebViewClient() {


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                loadingDialog.show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                loadingDialog.dismiss();
            }
        });

        mWebView.loadUrl(content);
    }

    @Override
    public void onCode() {
        getQrcodeLink();
    }

    @Override
    public void onCopy() {
        getShareRegisterLink();
    }

    public void getQrcodeLink() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getQrcodeLink().compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    checkPermission(new CheckPermListener() {
                        @Override
                        public void superPermission() {
                            if (isSava) {
                                ToastUtil.makeText(InviteActivity.this, "二维码已成功保存");
                                return;
                            }
                            Glide.with(InviteActivity.this).load(result.datas.url).asBitmap().into(new ImageViewTarget<Bitmap>(btnBack) {
                                @Override
                                protected void setResource(Bitmap resource) {
                                    saveImageToGallery(InviteActivity.this, resource);

                                }
                            });
                        }

                    }, R.string.camera_storage_card_p, R.string.ask_again, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                });
    }

    public void getShareRegisterLink() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getShareRegisterLink().compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
                    ClipData mClipData = ClipData.newPlainText("Label", result.datas.link);
// 将ClipData内容放到系统剪贴板里。
                    cm.setPrimaryClip(mClipData);
                    ToastUtil.makeText(this, "复制成功").show();
                });
    }


    private class JsToJava1 {
        //这里需要加@JavascriptInterface，4.2之后提供给javascript调用的函数必须带有@JavascriptInterface
        @JavascriptInterface
        public void saveQrCode(String url) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!checkLogin()) {
                        return;
                    }
                    if (isSava) {
                        ToastUtil.makeText(InviteActivity.this, "二维码已成功保存");
                        return;
                    }
                    checkPermission(new CheckPermListener() {
                        @Override
                        public void superPermission() {
                            Glide.with(InviteActivity.this).load(url).asBitmap().into(new ImageViewTarget<Bitmap>(btnBack) {
                                @Override
                                protected void setResource(Bitmap resource) {
                                    saveImageToGallery(InviteActivity.this, resource);

                                }
                            });
//                            saveImageToGallery(InviteActivity.this, QRCode.createQRCodeWithLogo5(url, 500, BitmapFactory.decodeResource(getResources(), R.mipmap.img_icon)));
                        }

                    }, R.string.camera_storage_card_p, R.string.ask_again, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//                    getCreateOrder(product_id, payment_id);
                }
            });

        }

        @JavascriptInterface
        public void goCosn() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!checkLogin()) {
                        return;
                    }
                    Util.startActivity(InviteActivity.this, MyCommissionActivity.class);
//                    getCreateOrder(product_id, payment_id);
                }
            });
        }
    }


    public void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "hmx");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
        ToastUtil.makeText(context, "保存成功").show();
        isSava = true;
    }


//    private class JsToJava2 {
//        //这里需要加@JavascriptInterface，4.2之后提供给javascript调用的函数必须带有@JavascriptInterface
//
//    }

    private boolean checkLogin() {
        if (UserInfoGlobal.isLogin()) {
            return true;
        } else {
            Dialog.showDefaultDialog(this, "", "登录后才能发起分享是否马上去登录？", "取消", "登录", false, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    Intent intent = new Intent(InviteActivity.this, LoginNewActivity.class);
                    intent.putExtra("is_from_invite", true);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                }

                @Override
                public void cancel() {

                }
            });
            return false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mWebContainer.removeAllViews();
        if (mWebView != null) {
            mWebView.onPause();
            mWebView.destroy();
            mWebView = null;
        }
        unbiner.unbind();
        unbiner = null;
    }


    @OnClick({R.id.btn_back, R.id.btn_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_share:
                if (checkLogin()) {
                    inviteShareDilaog.show();
                }
                break;
        }
    }
}
